package com.stars.easyms.redis.interceptor;

import com.stars.easyms.redis.annotion.RedisStringSet;
import com.stars.easyms.redis.exception.RedisInterceptorException;
import com.stars.easyms.base.util.TimeUtil;
import org.aopalliance.intercept.MethodInvocation;

import java.util.concurrent.TimeUnit;

/**
 * <p>className: RedisStringSetInterceptor</p>
 * <p>description: RedisStringSet注解拦截器</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019-03-18 13:55
 */
public class RedisStringSetInterceptor extends AbstractRedisInterceptor<RedisStringSet> {

    @Override
    protected Object invoke(MethodInvocation methodInvocation, RedisStringSet redisStringSet) throws RedisInterceptorException {
        Object result = proceed(methodInvocation);
        if (isEnabled() && result != null) {
            String redisKey = getRedisKey(methodInvocation, redisStringSet.group());
            Long expire = getExpire(methodInvocation);
            expire = expire != null ? expire : TimeUtil.parseToMilliseconds(redisStringSet.expire());
            boolean isSetExpire = expire != null && expire > 0 && (redisStringSet.resetExpire() || easyMsRedisTemplate.getExpire(redisKey, TimeUnit.MILLISECONDS) <= 0);
            if (isSetExpire) {
                if (redisStringSet.onlyAbsent()) {
                    easyMsRedisTemplate.setIfAbsent(redisKey, result, expire, TimeUnit.MILLISECONDS);
                } else {
                    easyMsRedisTemplate.set(redisKey, result, expire, TimeUnit.MILLISECONDS);
                }
            } else {
                if (redisStringSet.onlyAbsent()) {
                    easyMsRedisTemplate.setIfAbsent(redisKey, result);
                } else {
                    easyMsRedisTemplate.set(redisKey, result);
                }
            }
        }
        return result;
    }

}